import { Router, Request, Response } from 'express'
import { v4 as uuidv4 } from 'uuid'
import { getDatabase } from '../database/init'
import { smartParse, decomposeTask, generateSuggestions, intelligentSearch } from '../services/openai'
import { generateAIContext, trackUserBehavior, getUserStats } from '../services/userBehavior'
import { authenticateToken, optionalAuth } from '../middleware/auth'

const router = Router()

// 智能解析和任务分解不需要强制认证，但如果有用户信息会更好
router.use('/smart-parse', optionalAuth)
router.use('/decompose', optionalAuth)

// 个性化功能需要认证
router.use('/personalized-suggestions', authenticateToken)
router.use('/search', authenticateToken)
router.use('/suggestion-feedback', authenticateToken)
router.use('/user-stats', authenticateToken)

// 智能解析自然语言输入
router.post('/smart-parse', async (req: Request, res: Response) => {
  try {
    const { text } = req.body
    
    if (!text) {
      return res.status(400).json({ error: '输入文本不能为空' })
    }
    
    // 使用OpenAI进行智能解析
    const result = await smartParse(text)
    
    if (result.success) {
      res.json(result)
    } else {
      // 如果AI解析失败，使用fallback结果
      const errorResult = result as any // 类型断言处理
      res.json({
        success: true,
        result: errorResult.fallback || errorResult.result,
        message: 'AI解析失败，使用基础解析结果',
        warning: errorResult.error || errorResult.message
      })
    }
  } catch (error) {
    console.error('智能解析失败:', error)
    res.status(500).json({ error: '智能解析失败' })
  }
})

// 任务分解
router.post('/decompose', async (req: Request, res: Response) => {
  try {
    const { title, description } = req.body
    
    if (!title) {
      return res.status(400).json({ error: '任务标题不能为空' })
    }
    
    // 使用OpenAI进行任务分解
    const result = await decomposeTask(title, description)
    
    if (result.success) {
      res.json(result)
    } else {
      // 如果AI分解失败，使用fallback结果
      res.json({
        success: true,
        subtasks: result.fallback,
        message: 'AI任务分解失败，使用基础分解结果',
        warning: result.error
      })
    }
  } catch (error) {
    console.error('任务分解失败:', error)
    res.status(500).json({ error: '任务分解失败' })
  }
})

// 智能建议
router.get('/suggestions', async (req: Request, res: Response) => {
  try {
    const db = getDatabase()
    
    // 获取当前用户的任务数据
    const tasksResult = await db.query(`
      SELECT id, title, priority, category, completed, created_at
      FROM tasks
      WHERE user_id = $1
      ORDER BY created_at DESC
      LIMIT 20
    `, [req.userId])
    
    const tasks = tasksResult.rows.map((row: any) => ({
      ...row,
      createdAt: row.created_at
    }))
    
    // 使用OpenAI生成智能建议
    const result = await generateSuggestions(tasks)
    
    if (result.success) {
      res.json(result)
    } else {
      // 如果AI建议生成失败，使用fallback结果
      res.json({
        success: true,
        suggestions: result.fallback,
        message: 'AI建议生成失败，使用基础建议',
        warning: result.error
      })
    }
  } catch (error) {
    console.error('获取智能建议失败:', error)
    res.status(500).json({ error: '获取智能建议失败' })
  }
})

// 智能搜索
router.post('/search', async (req: Request, res: Response) => {
  try {
    const { query } = req.body
    
    if (!query) {
      return res.status(400).json({ error: '搜索查询不能为空' })
    }
    
    const db = getDatabase()
    
    // 获取当前用户的任务数据用于AI分析
    const tasksResult = await db.query(`
      SELECT id, title, priority, category, tags, created_at
      FROM tasks
      WHERE user_id = $1
      ORDER BY created_at DESC
      LIMIT 50
    `, [req.userId])
    
    const tasks = tasksResult.rows.map((row: any) => ({
      ...row,
      createdAt: row.created_at
    }))
    
    // 使用OpenAI进行智能搜索
    const result = await intelligentSearch(query, tasks)
    
    if (result.success) {
      res.json(result)
    } else {
      // 如果AI搜索失败，使用fallback结果
      res.json({
        success: true,
        ...result.fallback,
        message: 'AI搜索失败，使用基础搜索',
        warning: result.error
      })
    }
  } catch (error) {
    console.error('智能搜索失败:', error)
    res.status(500).json({ error: '智能搜索失败' })
  }
})

// 生成个性化建议（基于用户行为）
router.post('/personalized-suggestions', async (req: Request, res: Response) => {
  try {
    const { context, mode, taskId } = req.body as { context?: string; mode?: 'dashboard' | 'task'; taskId?: string }
    
    const db = getDatabase()
    
    // 根据模式获取任务数据，task 模式仅查询单任务
    let tasksResult
    if (mode === 'task' && taskId) {
      tasksResult = await db.query(`
        SELECT id, title, priority, category, completed, created_at, updated_at,
               is_recurring, recurring_type, recurring_pattern, parent_recurring_id,
               due_date, reminder_minutes
        FROM tasks
        WHERE user_id = $1 AND id = $2
        LIMIT 1
      `, [req.userId, taskId])
    } else {
      tasksResult = await db.query(`
        SELECT id, title, priority, category, completed, created_at, updated_at,
               is_recurring, recurring_type, recurring_pattern, parent_recurring_id,
               due_date, reminder_minutes
        FROM tasks
        WHERE user_id = $1
        ORDER BY created_at DESC
        LIMIT 30
      `, [req.userId])
    }
    
    const tasks = tasksResult.rows.map((row: any) => ({
      ...row,
      createdAt: row.created_at,
      updatedAt: row.updated_at,
      dueDate: row.due_date,
      isRecurring: row.is_recurring,
      recurringType: row.recurring_type,
      recurringPattern: row.recurring_pattern,
      parentRecurringId: row.parent_recurring_id,
      reminderMinutes: row.reminder_minutes
    }))
    
    // 附加场景信息帮助模型遵循约束
    const sceneContext = `${context || ''}\n场景: ${mode === 'task' ? 'task' : 'dashboard'}${mode === 'task' && taskId ? `\n聚焦任务ID: ${taskId}` : ''}`
    
    // 使用OpenAI生成个性化建议
    const result = await generateSuggestions(tasks, sceneContext)
    
    if (result.success) {
      res.json(result)
    } else {
      res.json({
        success: true,
        suggestions: result.fallback,
        message: '个性化建议生成失败，使用基础建议',
        warning: result.error
      })
    }
  } catch (error) {
    console.error('生成个性化建议失败:', error)
    res.status(500).json({ error: '生成个性化建议失败' })
  }
})

// 建议反馈API
router.post('/suggestion-feedback', async (req: Request, res: Response) => {
  try {
    const { suggestionId, action, rating, feedbackText } = req.body
    
    // 记录建议反馈行为 - 使用允许的动作类型
    await trackUserBehavior({
      userId: req.userId!,
      action: 'suggestion_rate', // 使用允许的动作类型
      entityType: 'suggestion',
      entityId: suggestionId,
      metadata: { 
        action, 
        rating, 
        feedbackText,
        timestamp: new Date().toISOString()
      }
    })
    
    const db = getDatabase()
    
    // 存储详细反馈 - 修复字段名
    await db.query(`
      INSERT INTO suggestion_feedback (id, user_id, suggestion_id, feedback_type)
      VALUES ($1, $2, $3, $4)
    `, [
      uuidv4(),
      req.userId,
      suggestionId,
      action === 'accept' ? 'accept' : action === 'dismiss' ? 'dismiss' : 'snooze'
    ])
    
    res.json({ 
      success: true, 
      message: '反馈记录成功',
      action,
      rating 
    })
  } catch (error) {
    console.error('记录建议反馈失败:', error)
    res.status(500).json({ error: '记录建议反馈失败' })
  }
})

// 用户行为统计API
router.get('/user-stats/:userId?', async (req: Request, res: Response) => {
  try {
    // 只允许查看自己的统计数据，忽略路径参数
    const userId = req.userId!
    const days = parseInt(req.query.days as string) || 30
    
    const stats = await getUserStats(userId, days)
    
    res.json({
      success: true,
      stats,
      period: `${days}天`,
      generatedAt: new Date().toISOString()
    })
  } catch (error) {
    console.error('获取用户统计失败:', error)
    res.status(500).json({ error: '获取用户统计失败' })
  }
})

// AI动作参数解析API
router.post('/parse-action-parameters', async (req: Request, res: Response) => {
  try {
    const { suggestion, action, taskContext } = req.body
    
    if (!suggestion || !action) {
      return res.status(400).json({ error: '缺少必要参数' })
    }
    
    // 导入智能参数解析函数
    const { parseActionParameters } = require('../services/openai')
    
    const result = await parseActionParameters(suggestion, action, taskContext)
    
    if (result.success) {
      res.json(result)
    } else {
      res.status(500).json({ error: '参数解析失败', details: result.error })
    }
  } catch (error) {
    console.error('AI动作参数解析失败:', error)
    res.status(500).json({ error: 'AI动作参数解析失败' })
  }
})

// 批量解析动作参数API
router.post('/batch-parse-actions', async (req: Request, res: Response) => {
  try {
    const { suggestions, taskContext } = req.body
    
    if (!suggestions || !Array.isArray(suggestions)) {
      return res.status(400).json({ error: '缺少建议数据' })
    }
    
    // 导入批量解析函数
    const { batchParseActionParameters } = require('../services/openai')
    
    const results = await batchParseActionParameters(suggestions, taskContext)
    
    res.json({
      success: true,
      results,
      message: '批量参数解析完成'
    })
  } catch (error) {
    console.error('批量解析动作参数失败:', error)
    res.status(500).json({ error: '批量解析动作参数失败' })
  }
})

export { router as aiRoutes }
